import { createRouter, createWebHistory } from 'vue-router'
import store from '../store'

const routes = [
  {
    path: '/',
    redirect: '/home',
    component: () => import('../views/Home.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/home',
    name: '/Home',
    component: () => import('../views/Home.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/weatherSet',
    name: 'WeatherSet',
    component: () => import('../views/WeatherSet.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/geometry',
    name: 'Geometry',
    component: () => import('../views/Geometry.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/object',
    name: 'Object',
    component: () => import('../views/Object.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/camera',
    name: 'Camera',
    component: () => import('../views/Camera.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/capture',
    name: 'Capture',
    component: () => import('../views/Capture.vue'),
    meta: { requiresAuth: true }
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = store.state.user.token

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!token) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    if (token && to.path === '/login') {
      next('/')
    } else {
      next()
    }
  }
})

export default router
